<!-- 支出计划 -->
<template>
  <div class="revenue-box expenditure-box">
    <!-- 编制中 -->
    <el-collapse v-model="activeNames1" v-if="type == 1">
      <el-collapse-item v-for="(item, index) in collapseData1" :key="index" :name="index">
        <template slot="title">
          <div>
            <span>{{ item.chargeItemName }}</span>
            <span style="padding-right: 10px">年计划支出{{ item.plannedIncome | formatMoney }}元</span>
            <span>比去年计划支出{{ GetUp(item.lastIncome) ? '增加' : '减少' }}</span>
            <span :class="{ 'clolor-blue': GetUp(item.lastIncome), 'clolor-red': !GetUp(item.lastIncome) }">{{ item.lastIncome | formatMoney }}元</span>
            <span>同比{{ GetUp(item.increase) ? '增加' : '减少' }}</span>
            <span :class="{ 'clolor-blue': GetUp(item.increase), 'clolor-red': !GetUp(item.increase) }">{{ item.increase }}</span>
            比去年执行支出{{ GetUp(item.executiveIncome) ? '增加' : '减少' }}
            <span :class="{ 'clolor-blue': GetUp(item.executiveIncome), 'clolor-red': !GetUp(item.executiveIncome) }">{{ item.executiveIncome | formatMoney }}元</span>
            <span>同比{{ GetUp(item.executiveIncomeIncrease) ? '增加' : '减少' }}</span>
            <span :class="{ 'clolor-blue': GetUp(item.executiveIncomeIncrease), 'clolor-red': !GetUp(item.executiveIncomeIncrease) }">{{ item.executiveIncomeIncrease }}</span>
          </div>
        </template>
        <el-table :data="item.child" style="width: 100%" border row-key="categoryGroup" default-expand-all :tree-props="{children: 'child'}">
          <template v-for="(col) in Columns1(item)">
            <el-table-column :key="col.categoryGroup" :prop="col.prop" :label="col.label" :width="col.width ? col.width : null" :align="col.align ? col.align : null" :min-width="col.minwidth ? col.minwidth : null">
              <template slot-scope="scope">
                <div class="cursor-pointer" v-if="col.prop == 'chargeItemName'" @click="rowClick(item, scope.row, col)">{{ col.customRender ? col.customRender(scope.row, scope.row[col.prop]) : scope.row[col.prop] }}</div>
                <div class="cursor-pointer" v-else @click="rowClick(item, scope.row, col)">{{ (col.customRender ? col.customRender(scope.row, scope.row[col.prop]) : scope.row[col.prop]) | formatMoney }}</div>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </el-collapse-item>
    </el-collapse>

    <div v-if="type == 2">
      <el-collapse v-model="activeNames2">
        <el-collapse-item v-for="(item, index) in collapseData2" :key="index" :name="index">
          <template slot="title">
            <div>
              {{ item.chargeItemName + '截止 ' + item.planYear + ' 年 ' + item.planMonth + ' 月，年累计执行' }}{{ item.cumulativeExecution | formatMoney }}{{ '元，计划执行进度' + item.planExecutionProgress }}
              <span v-if="item.belowPlanPercentage" :class="{ 'clolor-blue': GetUp(item.belowPlanPercentage), 'clolor-red': !GetUp(item.belowPlanPercentage) }">({{ item.belowPlanPercentage }})</span>
              {{ '预计全年支出' }}{{ item.calculateAmount | formatMoney }}{{ '元，比去年执行支出' + item.higherThanPlanned + '' }}
              <span :class="{ 'clolor-blue': GetUp(item.plannedPercentage), 'clolor-red': !GetUp(item.plannedPercentage) }">({{ item.plannedPercentage }})</span>
            </div>
          </template>
          <el-table :data="item.child" style="width: 100%" border row-key="categoryGroup" default-expand-all :tree-props="{children: 'child'}">
            <template v-for="(col) in Columns2(item)">
              <template v-if="col.children">
                <el-table-column :label="col.label" :key="col.categoryGroup" :class-name="col.classname" :align="col.align">
                  <el-table-column v-for="(col2) in col.children" :class-name="col2.classname" :key="col2.categoryGroup" :prop="col2.prop" :label="col2.label" :width="col2.width ? col2.width : null" :align="col2.align ? col2.align : null" :min-width="col2.minwidth ? col2.minwidth : null">
                    <template slot-scope="scope">
                      <div class="cursor-pointer" @click="rowClick(item, scope.row, col2)">{{ (col2.customRender ? col2.customRender(scope.row, scope.row[col2.prop]) : scope.row[col2.prop]) | formatMoney }}</div>
                    </template>
                  </el-table-column>
                </el-table-column>
              </template>
              <template v-else>
                <el-table-column :key="col.categoryGroup" :prop="col.prop" :label="col.label" :width="col.width ? col.width : null" :align="col.align ? col.align : null" :min-width="col.minwidth ? col.minwidth : null">
                  <template slot-scope="scope">
                    <div  v-if="col.prop == 'chargeItemName'">{{ col.customRender ? col.customRender(scope.row, scope.row[col.prop]) : scope.row[col.prop] }}</div>
                    <div v-else>{{ (col.customRender ? col.customRender(scope.row, scope.row[col.prop]) : scope.row[col.prop]) | formatMoney }}</div>
                  </template>
                </el-table-column>
              </template>
            </template>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </div>

    <!-- 添加更进 -->
    <!--电梯大修、空调保养费用、空气质量检测费用、电梯维修设备、新增设备设施-->
    <el-dialog title="详细信息" :visible="showDialog" width="65%" :before-close="closeDialogUpdate" :close-on-click-modal="false">
      <personExpenditure ref="personExpenditure" :isEdit='isEdit' :assetCode="assetCode" :personData="dialogData" v-if="showPerson" @close-dialog2="closeFurther2" />
      <monthExpenditure ref="monthExpenditure" :isEdit='isEdit' :assetCode="assetCode" :monthData="dialogData" v-if="showMonth"  @close-dialog2="closeFurther2" />
      <equipmentExpenditure ref="equipmentExpenditure" :isEdit='isEdit' :assetCode="assetCode" :equipmentData="dialogData" v-if="showEquipment" @close-dialog2="closeFurther2" />
    </el-dialog>
    <!--点击支出计划 支出事项-->
    <historicalPlan v-if="showHistoricalPlan"  @close-dialog="closeDialog" :name="typeName" :type.sync="typeNumber" :assetCode="assetCode"></historicalPlan>
  </div>
</template>
<script>
import historicalPlan from '../planTab/components/historicalPlan.vue';
import personExpenditure from './components/dialogExpenditure/personExpenditure';
import monthExpenditure from './components/dialogExpenditure/monthExpenditure';
import equipmentExpenditure from './components/dialogExpenditure/equipmentExpenditure';
import Api from '../../api/incomeAndExpenditurePlan';
export default {
  data() {
    return {
      showDialog:false,
      dialogData:{},
      isEdit: false,
      m_MenuVisible: false,
      m_MenuItemList: [],
      showPerson: false,
      showMonth: false,
      showEquipment: false,
      type: this.$route.query.type ? this.$route.query.type : 1,
      showHistoricalPlan: false,
      typeName: '',
      value: 'zichan',
      options: [
        {
          value: 'zichan',
          label: '资产',
        },
      ],
      activeNames1: [],
      activeNames2: [],
      collapseData1: [],
      collapseData2: [],
      month: null,
      curData: null,
      chargeItemGroupType: null,
      matters: [],
      typeNumber: 2,
      assetCode:'',
      isEdit:''
    };
  },
  mounted() {},
  computed: {
    Columns1() {
      return function (item) {
        let align = 'center';
        let width = null;
        let columns = [
          {
            label: '支出事项',
            prop: 'chargeItemName',
            align: 'left',
            width: '300',
          },
          {
            label: '计划支出',
            prop: 'plannedIncome',
            align: align,
            width: '180',
          },
          {
            label: '上一财年支出',
            prop: 'preYearCalculateAmount',
            align: align,
            width: '180',
          },
        ];
        for (let i = 0; i < 12; i++) {
          columns.push({
            label: (this.planDetail.planYear ? this.planDetail.planYear : '') + '年' + (i + 1) + '月支出现金流',
            classname: this.month == i + 1 ? 'active' : '',
            width: '190',
            align: align,
            prop: 'monthMap',
            month: i + 1,
            customRender: (row, text) => {
              if (text) {
                return text[i + 1].cashIncome;
              }
              return '';
            },
          });
        }
        return columns;
      };
    },
    Columns2() {
      return function (item) {
        let align = 'center';
        let width = null;
        let columns = [
          {
            label: '支出事项',
            prop: 'chargeItemName',//1权责 2现金流
            align: 'left',
            width: '300',
          },
          {
            label: '计划全年支出',
            prop: 'currYearCalculateAmount',
            align: align,
            width: '180',
          },
          {
            label: '预测全年支出',
            prop: 'calculateAmount',
            align: align,
            width: '180',
          },
          {
            label: '偏差度',
            prop: 'plannedPercentage',
            align: align,
            width: '100',
          },
          {
            label: '全年执行支出',
            prop: 'cumulativeExecution',
            align: align,
            width: '180',
          },
          {
            label: '执行进度',
            prop:'planExecutionProgress',
            align: align,
            width: '100',
          },
        ];
        let strkey = 'cashIncome';
        let children1 = [];
        let children2 = [];
        let m = parseInt(item.planMonth) - 1;
        for (let i = 1; i <= m; i++) {
          children1.push({
            label: i + '月',
            month: i,
            classname: this.month == i ? 'active' : 'bk-grey',
            prop: 'monthMap',
            customRender: (row, text) => {
              if (text) {
                return text[i] ? text[i][strkey] : '-';
              }
              return '';
            },
            align: align,
            width: '190',
          });
        }
        for (let i = m + 1; i <= 12; i++) {
          children2.push({
            label: i + '月',
            month: i,
            classname: this.month == i ? 'active' : '',
            prop: 'monthMap',
            customRender: (row, text) => {
              if (text) {
                return text[i] ? text[i][strkey] : '-';
              }
              return '';
            },
            align: align,
            width: '190',
          });
        }
        if(children1&&children1.length>0){
          columns.push({
            align: align,
            label: '实际执行收入',
            children: children1,
          })
        }
        if(children2&&children2.length>0){
          columns.push({
            align: align,
            label: '预测收入',
            children: children2,
          })
        }

        return columns;
      };
    },
    isdisabled() {
      // return false
      if (this.$route.path.indexOf('/businessManage/') < 0) return true;
      if (this.planDetail) return this.planDetail.status != 4 || this.$route.query.processWorkId;
      return true;
    },
    planDetail() {
      return this.$store.state.planDetail;
    },
  },
  watch: {
    planDetail: {
      handler(plandetail) {
        if (plandetail) {
          this.month = plandetail.month;
          this.getData();
        }
      },
    },
  },
  methods: {
    GetUp(str) {
      if (!str) return false;
      if (str.indexOf('+') > -1) return true;
      return false;
    },
    getData() {
      this.planKey = this.$route.query.planKey;
      if (this.type == 1) {
        Api['toCompileIncomePlan']({
          planKey:this.planKey,
          itemType:4,
          statusList:[1,2,4]
        }).then(res => {
          if (res && res.success) {
            this.collapseData1 = res.rows
          }
        });
      } else {
        Api['toPerformIncomePlan']({
          planKey: this.planKey,
          itemType:4,
          statusList:[1,2,4]
        }).then(res => {
          if (res && res.success) {
            res.rows.forEach((ele,index)=>{
              ele.id=ele.categoryGroup
            })
            this.collapseData2 = res.rows;
          }
        });
      }
    },
    closeFurther2(val) {
      this.getData()
      this.showPerson = val
      this.showMonth = val;
      this.showDialog = val
      this.showEquipment = val
    },

    async rowClick(item, row, col) {
      if(row.chargeItemCategory==2||row.chargeItemCategory==3){
        this.assetCode = row.assetCode
        if (col.label == '支出事项' && this.type == 2) {
          this.showHistoricalPlan = true;
          this.typeName = row.chargeItemName;
          return;
        }
        this.isEdit = row.isEdit
        if(row.chargeItemType==0){
          return
        }
        const res = await Api.income({
          assetKey:row.assetKey,
          assetCode:row.assetCode,
          billConfigKey: row.monthMap[col.month].billConfigKey, // row.billConfigKey,
          chargeItemType:row.chargeItemType,
          planKey:this.$route.query.planKey
        });
        if (res && res.success) {
          this.dialogData = res
          this.showDialog = true
          //人员成本支出
          if (row.chargeItemType == '6') {
            this.showPerson = true
            // this.showMonth=false
            // this.showEquipment=false
            setTimeout(() => {
              this.$refs.personExpenditure.init()
            }, 100);
          } else if (row.chargeItemType=='7') {
            // 设备维护支出
            this.showEquipment = true
            setTimeout(() => {
              this.$refs.equipmentExpenditure.init()
            }, 100);
          } else if (row.chargeItemType == '8') {
            //月份预估支出
            let list = []
            for (let i in row.monthMap) {
              list.push({
                month:i,
                paymentAmount: row.monthMap[i].cashIncome
              })
            }
            this.showMonth = true
            setTimeout(() => {
              this.$refs.monthExpenditure.init(list)
            }, 100);
          }
        }
      }
    },
    closeDialogUpdate(){
      this.showDialog = false
      this.showPerson = false
      this.showMonth = false
    },
    closeDialog() {
      this.showHistoricalPlan = false;
    },
  },
  filters: {
    formatMoney(s, type) {
      if (s == null || s == undefined) return '-';
      s = s.toString();
      let negative = false;
      // è´Ÿæ•°
      if (s.slice(0, 1) === '-') {
        negative = true;
        s = s.slice(1);
      }
      if (s.slice(0, 1) === '+') {
        s = s.slice(1);
      }

      if (/[^0-9\.]/.test(s)) return '0';
      if (s == null || s == '') return '0';
      s = s.toString().replace(/^(\d*)$/, '$1.');
      s = (s + '00').replace(/(\d*\.\d\d)\d*/, '$1');
      s = s.replace('.', ',');
      var re = /(\d)(\d{3},)/;
      while (re.test(s)) s = s.replace(re, '$1,$2');
      s = s.replace(/,(\d\d)$/, '.$1');
      if (type == 0) {
        // ä¸å¸¦å°æ•°ä½(é»˜è®¤æ˜¯æœ‰å°æ•°ä½)
        var a = s.split('.');
        if (a[1] == '00') {
          s = a[0];
        }
      }
      return `¥${negative ? '-' : ''}${s}`;
    },
  },
  components: { historicalPlan, personExpenditure, monthExpenditure, equipmentExpenditure },
};
</script>
<style lang="scss">

.expenditure-box {
  padding: 30px;
  .btn-submit {
    position: fixed;
    top: 14px;
    right: 310px;
    z-index: 9999;
  }
  .active {
    background: #eff5ff !important;
  }
  .bk-grey {
    background: #f5f7fa;
  }
  .clolor-red {
    color: #ff0000;
    padding-right: 10px;
  }
  .clolor-blue {
    color: #29c37f;
    padding-right: 10px;
  }
}
</style>
